package com.innovation.ic.sc.base.thread.listener.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.innovation.ic.sc.base.model.erp9_pvecrm.SpecialsSCTopView;
import com.innovation.ic.sc.base.pojo.constant.handler.RabbitMqConstants;
import com.innovation.ic.sc.base.service.sc.AdvantageModelService;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;

/**
 * @desc   监听优势型号新增/修改/延期队列
 * @author linuo
 * @time   2022年10月18日13:58:49
 */
public class ListenAdvantageModelAddQueueThread extends AbstractRabbitmqThread implements Runnable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Channel channel;
    private AdvantageModelService advantageModelService;

    public ListenAdvantageModelAddQueueThread(Channel channel, AdvantageModelService advantageModelService) {
        this.channel = channel;
        this.advantageModelService = advantageModelService;
    }

    @Override
    @SneakyThrows
    public void run() {
        String exchange = RabbitMqConstants.SC_ERP_EXCHANGE;
        //String queue = RabbitMqConstants.ERP_TO_SC_QUEUE_NAME;
        String routingKey = RabbitMqConstants.ERP_SC_ADD_QUEUE;
        final String queue = routingKey;
        channel.queueBind(queue, exchange, routingKey);
        channel.queueDeclare(queue, true, false, false, null);
        channel.exchangeDeclare(exchange, RabbitMqConstants.DIRECT_TYPE, true);
        Consumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String bodyString = new String(body);
                logger.info("接收到的队列:[{}]的消息为:[{}]", queue, bodyString);
                try {
                    if (!Strings.isNullOrEmpty(bodyString)) {
                        // 获取消息体中的数据内容
                        String messageBody = getMessageBody(bodyString);
                        if (!Strings.isNullOrEmpty(messageBody)) {
                            SpecialsSCTopView specialsScTopView = JSONObject.parseObject(messageBody, SpecialsSCTopView.class);

                            // 处理优势型号新增/修改/延期信息
                            if (specialsScTopView != null && !Strings.isNullOrEmpty(specialsScTopView.getPartNumber()) && !Strings.isNullOrEmpty(specialsScTopView.getBrand())) {
                                advantageModelService.handleAdvantageModelAddMqMsg(specialsScTopView);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("监听队列:[{}]时出现问题,原因:", queue, e);
                }
            }
        };
        channel.basicConsume(queue, true, callback);
    }
}